package com.zgkj.Zip.tools;


import java.io.File;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.zgkj.Zip.form.NoticeListInf;

public class XMLToBean {
	private  NoticeListInf noticelistinf;

	public XMLToBean(String filepath) throws Exception{
		this.noticelistinf = new NoticeListInf();
		SAXReader reader = new SAXReader();
        Document doc = null;
		try {
			doc = reader.read(new File(filepath));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Element root = doc.getRootElement();
        listNodes(root);
	}
	public NoticeListInf getNoticelistinf() {
		return noticelistinf;
	}

	public void setNoticelistinf(NoticeListInf noticelistinf) {
		this.noticelistinf = noticelistinf;
	}

	public  void listNodes(Element node) throws Exception{
	       // System.out.println("当前节点的名称：" + node.getName());
	        Field[] fields = NoticeListInf.class.getDeclaredFields();
	        for (Field field : fields){
	        	  field.setAccessible(true);
	              String name = field.getName().toUpperCase();
	              if(name.equals(node.getName()) ){
		              if (field.getType().equals(Long.class) || field.getType().equals(long.class))
	                  {
	                      field.set(this.noticelistinf, Long.parseLong(node.getTextTrim()));
	                  }
	                  else if (field.getType().equals(String.class))
	                  {
	                      field.set(this.noticelistinf, node.getTextTrim());
	                  }
	                  else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
	                  {
	                      field.set(this.noticelistinf, Double.parseDouble(node.getTextTrim()));
	                  }
	                  else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
	                  {
	                      field.set(this.noticelistinf, Integer.parseInt(node.getTextTrim()));
	                  }
	                  else if (field.getType().equals(java.util.Date.class))
	                  {
	                      field.set(this.noticelistinf, Date.parse(node.getTextTrim()));
	                  }
	                  else
	                  {
	                      continue;
	                  }
	              }

			}
	        Iterator<Element> iterator = node.elementIterator();
	        while(iterator.hasNext()){
	            Element e = iterator.next();
	            listNodes(e);
	        }
	    }

	public static void main(String[] args) throws Exception {
        XMLToBean XMLToBean = new XMLToBean("D:/list.xml");
        XMLToBean.getNoticelistinf().getFawenr();
	}
}
